<template>
  <dialog_item :dialogTitle="$t('select_user')" @onBtnDialogClick="onBtnDialogClick"  :visible.sync="dialogVisible"  dialogClass="user-selectbox dialogHeight" :appendBody="true" :isShowConfirmBtn="true">
    <el-container>
      <el-row :gutter="24" class="width100 margin0">
        <el-col :span="6" class="border-r">
        <!-- 没有checkbox的tree -->
          <el-tree
            ref="tree"
            node-key="id"
            :props="{
                  label: 'name',
                  children: 'zones',
                  isLeaf: 'leaf'
                }"
            :load="loadNode"
            :show-checkbox="showBox"
            check-strictly
            :default-expanded-keys="defaultExpandedKeys"
            :expand-on-click-node="false"
            @node-click="onNodeClick"
            :key="timer"
            lazy
          >
          <span class="custom-tree-node over-ellipsis" slot-scope="{ node, data }">
            <span :title="data.name">{{ node.label }}</span>
          </span>
          </el-tree>
        </el-col>
        <el-col :span="18" class="paddingRight0">
          <el-form :inline="true" :model="searchdata" class="form-inline searchForm paddingT0" size="mini"  @submit.native.prevent>
            <el-form-item  class="paddingLeft0">
              <el-input v-model="searchdata.data.searchWord" :placeholder="$t('user_name')+'/'+$t('loginno')" @keyup.enter.native="searchTableData"></el-input>
            </el-form-item>
            <el-form-item  class="paddingLeft0">
                <el-select v-model="searchdata.departmentid" filterable class="el-select-w">
                  <el-option
                    :label="$t('please_select_dept')"
                    value="">
                    </el-option>
                  <el-option v-for="item in depts.datas" 
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            <el-form-item>
              <el-button @click="searchTableData" type="primary" plain >{{$t('query')}}</el-button>
              <el-button @click="resetSearchTableData">{{$t('reset')}}</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="tableData.datas" 
            @selection-change='selectUser'
            max-height="350" 
            highlight-current-row
            size="small">
            <el-table-column type="selection" width="55" v-if="tableData.datas?tableData.datas.length>0:false">
            </el-table-column>
            <el-table-column prop="name" :label="$t('username')"></el-table-column>
            <el-table-column prop="loginno" :label="$t('loginno')"></el-table-column>
            <el-table-column prop="email" :label="$t('email')"></el-table-column>
            <el-table-column prop="telephone" :label="$t('tel')"></el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="searchTableData"
            :current-page.sync="searchdata.currpage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="searchdata.pagelines"
            layout="prev, pager, next, total, sizes"
            background
            :total="tableData.rowCount?tableData.rowCount:0"
          ></el-pagination>
        </el-col>
      </el-row>
        
    </el-container>
    </dialog_item>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean
    },
    roleId:{
      type: String
    },
    updateBatchUser:{
      type: Boolean
    },
    applicationId:{
      type: String
    },
    docIdSelection:{
      type:Array
    },
    showBox:{
      type: Boolean,
      default: true
    }
  },

  data() {
    return {
      defaultExpandedKeys: [],
      node:[],
      resolve:function(){},
      isFirst:true,
      roleData: {},
      onlineData: {},
      searchdata: {
        domainid:this.$route.query.domainid,
        departmentid: "",
        currpage: 1,
        pagelines: 10,
        orderby: "",
        data:{
          searchWord: "",
          superiorname: "",
          roleid: "",
        }
      },
      tableData: [],
      tableDatabyRole: [],
      searchall: false,
      checkUser:[],
      depts:[],//部门列表
      timer:'',
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      }
    }
  },
  created() {
    this.searchTableData();
    this.loadNode(this.node,this.resolve);
    this.getDepts();
  },
  methods: {
    onBtnDialogClick(name){
      if(name=='confirm'){
        this.onOk()
      }
    },
    //获取部门列表
    getDepts(){
      let searchdata={...this.searchdata}
      searchdata.data={name: ""}
      this.$api.getSubDepartments({superiorid:"",valid:1,...searchdata,pagelines:100000}, {
        onSucess: resp => {
          this.depts = resp.data.data;
        }
      });
    },
    // 点击树更新列表的数据
    onNodeClick(dept) {
      this.searchdata.departmentid = dept.id
      this.searchTableData();
    },
    //勾选用户
    selectUser(selection){
      this.checkUser=[];
      if(selection.length>0){
        selection.forEach(elm=>{
          this.checkUser.push(elm.id)
        })
      }
    },
    onOk() {
      let checkDept = this.$refs.tree.getCheckedNodes();
      let checkedDept=[];
      checkDept.forEach(elm=>{
        checkedDept.push(elm.id)
      })
      // 流程面板中更新指定审批人
      if(this.updateBatchUser){
        let data = {
          "userIds":this.checkUser,
          "docs": this.docIdSelection
        }
        if(data.userIds.length<1){
          this.$message.error(this.$t("select_user_required"));
          return false;
        }
        this.$api.updateBatchUser(data, {
          onSucess: resp => {
            if(resp.data.data){
              this.$message({
                showClose: true,
                message: resp.data.data,
                type: "error"
              });
            } else{
              this.$message({
                showClose: true,
                message: '更新成功',
                type: "success"
              });
              this.dialogVisible = false;
              this.$parent.searchTableData()
            }
          }
        })
      }else{
        let data={
          "roleId":this.roleId,
          "deptIds":checkedDept,
          "userIds":this.checkUser
        }
        if(data.deptIds.length<1 ){
          this.$message.error(this.$t("please_select_dept_required"));
          return false;
        }else if(data.userIds.length<1){
          this.$message.error(this.$t("select_user_required"));
          return false;
        }
        this.$api.batchUser(data, {
          onSucess: resp => {
            if(resp.data.errcode==0){
              this.$message({
                showClose: true,
                message: this.$t('msg_add_success'),
                type: "success"
              });
              this.dialogVisible = false;

            }
            else{
              this.$message({
                showClose: true,
                message: this.$t("add_failed"),
                type: "error"
              });
            }
          }
        });
        }
    },
    onCancel() {
      this.dialogVisible = false;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    resetSearchTableData(){
      this.timer=new Date().getTime()
      this.searchdata={
        domainid: this.$route.query.domainid,
        departmentid: "",
        currpage: 1,
        pagelines: 10,
        orderby: "",
        data:{
          searchWord: "",
          superiorname: "",
          roleid: "",
        }
      };
      this.searchTableData();
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        if(this.isFirst){
          this.isFirst=false;
          this.node=node;
          this.resolve=this.resolve;
        }
        this.$api.getRootDepartment(this.$route.query.domainid, {
          onSucess: resp => {
            let rootDepartment = resp.data.data;
            resolve([rootDepartment]);
            this.defaultExpandedKeys.push(rootDepartment.id);
          }
        });
      }
      if (node.level >= 1) {
        this.$api.getSubDepartmentNodes(this.$route.query.domainid, node.key,1, {
          onSucess: resp => {
            let subdepts = resp.data.data;
            resolve(subdepts);
          }
        });
      }
    },
    handleSizeChange(size){
      this.searchdata.pagelines=size;
      this.searchTableData();
    },
    searchTableData() {
      this.searchdata.domainid = this.$route.query.domainid;
      this.searchdata.data.roleid = "";
      this.searchdata.data.status = 1
      this.$api.getUsers(this.searchdata, {
        onSucess: resp => {
          this.tableData = resp.data.data;
        }
      });
    },
  }

};
</script>

<style scoped>

</style>